package com.yohann.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yohann.oss.service.OssService;
import com.yohann.oss.utils.ConstantConfig;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * <p>
 * oss服务实现类
 * </p>
 *
 * @author Yohann
 * @since 2020/8/7
 */
@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String endpoint = ConstantConfig.END_POIND;
        String accessKeyId = ConstantConfig.END_KEYID;
        String accessKeySecret = ConstantConfig.END_KEYSECRET;
        String bucketName = ConstantConfig.END_BUCKETNAME;
        OSS ossClient = null;

        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            //当前文件名
            String fileName = file.getOriginalFilename();

            //随机生成文件名
            String uuid = UUID.randomUUID().toString().replaceAll("-","");

            //获取日期
            String datePath = new DateTime().toString("yyyy/MM/dd");

            //最终文件名
            fileName = datePath + "/" + uuid + fileName;

            //获取流数据
            InputStream inputStream = file.getInputStream();

            //提交
            ossClient.putObject(bucketName,fileName,inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            //返回URL
            return "https://"+ bucketName + "." + endpoint + "/" + fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}